const Router = require('koa-router');
const router = new Router();
const tools = require('../tools/tool')
const {db, QueryTypes} = require("../models/db");
const {updateInventoryByBill, clearData,initInventoryBeg} = require("./base")
// 删除用户
router.post('/zq/getInfo', async ctx => {
    try {
        let tenantId = ctx.user.tenantId;
        let toStart = await db.models['zqStart'].findOne({
            where: {
                tenantId
            }
        })
        let ret = ''
        if (toStart) {
            ret = toStart.toJSON()
            let zq = await db.models['zq'].findOne({
                where: {
                    tenantId,
                    isCurrent: 1
                }
            })
            ret.currentYm = zq.ym;
        }
        return ctx.suc('', ret);
    } catch (e) {
        console.log('zq/getInfo', e)
        return ctx.err('无返回数据')
    }
})
// 开启账户
router.post('/zq/start', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let ym = body.ym;
        let tenantId = user.tenantId;
        let uid = user.id;
        let ctime = tools.getTime()
        let save = {
            tenantId,
            cby: uid,
            cbyName: user.name,
            ym,
            ctime: ctime
        }
        let zqBeg = ym + '-01';
        let zqEnd = tools.getDayStart(zqBeg, 'end', 0)
        
        await db.transaction(async t => {
            await db.models['zqStart'].create(save, {transaction: t})
            await db.models['zq'].destroy({
                where: {
                    tenantId
                }
            }, {transaction: t})
            await db.models['goodsCost'].destroy({
                where: {
                    tenantId
                }
            }, {transaction: t})
            let zq = await db.models['zq'].create({
                tenantId,
                zqBeg,
                zqEnd,
                isCurrent: 1,
                ym,
                ctime,
                cby: uid,
            })
            let sqlmer = `merge into goods_cost a using(select a.tenantId,a.locationId,a.invId,a.unit,case when a.unit=b.unit1 then a.qty*b.spec else a.qty end qty,amount from init_goods  a INNER JOIN goods b on a.invId=b.id)
                  b on a.tenantId=b.tenantId and a.locationId=b.locationId and a.invId=b.invId
                  when not matched then insert(tenantId,zqId,locationId,invId,initC,initM) values(b.tenantId,${zq.id},b.locationId,b.invId,b.qty,b.amount); `
            await db.query(sqlmer, {type: QueryTypes.UPDATE}, {transaction: t})
            await db.query(`exec cal_cost @tenantId=${tenantId},@billType='all'`, {type: QueryTypes.UPDATE}, {transaction: t})
           // await initInventoryBeg(ctx)
        })
        return ctx.suc('已开启账套');
    } catch (e) {
        console.log('zq/getInfo', e)
        return ctx.err(e)
    }
})
// 账期列表
router.post('/zq/list', async ctx => {
    try {
        let tenantId = ctx.user.tenantId;
        let sql = `SELECT a.*,b.name cbyName,case when isCurrent=1 then '未结账' else '已结账' end state  from zq a INNER JOIN admin b on a.cby=b.id and a.tenantId=${tenantId} order by id desc`;
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        return ctx.suc('', list);
    } catch (e) {
        console.log('zq/getInfo', e)
        return ctx.err('无返回数据')
    }
})
router.post('/zq/fj', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let zqId = body.zqId;
        let ctime = tools.getTime()
        if (!zqId) {
            return ctx.err('会计期间不能为空');
        }
        let zq = await db.models['zq'].findOne({
            where: {
                id: zqId
            }
        })
        if (!zq) {
            return ctx.err('账期设置错误')
        }
        if (zq.isCurrent != 1) {
            return ctx.err('不能反结非当前期间');
        }
        await db.transaction(async t => {
            await db.models['goodsCost'].destroy({
                where: {
                    tenantId,
                    zqId
                }
            }, {transaction: t})
            await db.models['zq'].destroy({
                where: {
                    tenantId,
                    id: zqId
                }
            }, {transaction: t})
            let zq1 = await db.models['zq'].findOne({
                where: {
                    tenantId
                },
                order: [['id', 'desc']]
            })
            if(zq1) {
                await db.models['zq'].update({
                    isCurrent: 1,
                    ctime
                }, {
                    where: {
                        id: zq1.id
                    }
                }, {transaction: t})
            }
            else {
                await db.models['zqStart'].destroy({
                    where: {
                        tenantId
                    }
                })
                await db.models['inventory'].destroy({
                    where: {
                        tenantId
                    }
                })
                await db.models['inventoryDetail'].destroy({
                    where: {
                        tenantId
                    }
                })
            }
            await db.models['profitHist'].destroy({
                where: {
                    tenantId,
                    zqId
                }
            }, {transaction: t})
            if(ctx.user.isCard == 1) {
                let sql = `delete from card_info where cardId in(select id from card where zqId=${zqId} and isJz=1 and tenantId=${tenantId})`;
                await db.query(sql, {type: QueryTypes.UPDATE}, {transaction: t})
                await db.models['card'].destroy({
                    where: {
                        tenantId,
                        zqId,
                        isJz: 1
                    }
                }, {transaction: t})
            }
            let sqls = `exec cal_cost @tenantId=${tenantId},@billType='all',@isJz=0`
            await db.query(sqls, {type: QueryTypes.UPDATE}, {transaction: t})
        })
        return ctx.suc('反结成功');
        
    } catch (e) {
        console.log('zq/getInfo', e)
        return ctx.err('无返回数据')
    }
})
router.post('/zq/toClosed', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let ym = body.ym;
        if(!ym) {
            return ctx.err('没有账期');
        }
        if (!user.id) {
            return ctx.err('没有用户');
        }
        let zq = await db.models['zq'].findOne({
            where: {
                tenantId,
                ym
            }
        })
        if (!zq) {
            return ctx.err('未发现账期')
        }
        if (zq.isCurrent != 1) {
            return ctx.err('当前账期已结账')
        }
        // 更新当前利润表
        let ret = setProfit(ctx)
        if(!ret.stat) return ret

        return ret
        // return bill.toClosed(ym, tenantId.asInt(), user.id.asInt(), zq.id.asInt());


    } catch (e) {
        console.log('zq/getInfo', e)
        return ctx.err('无返回数据')
    }
})
router.post('/zq/test', async ctx => {
    try {
        await updateInventoryByBill(ctx, 0, 522026)
    } catch (e) {
        console.log(e)
    }
    return ctx.suc('成功')
})
router.post('/zq/clearData', async ctx => {
    try {
        await clearData(ctx)
    } catch (e) {
        console.log(e)
    }
    return ctx.suc('成功')
})

const setProfit = async (ctx) => {
    let body = ctx.request.body
    let ym = body.ym
    let user = ctx.user
    let tenantId = user.tenantId;
    let sqls = `exec card_jz @tenantId=${tenantId},@ym='${ym}'`
    await db.query(sqls, {type: QueryTypes.UPDATE})
    let lists = await db.models['profit'].findAll({
        where: {
            tenantId
        }
    })
    let yb = ym.substring(0, 4) + "-01-01"
    let mb = ym + "-01"
    let me = tools.getDayStart(mb,'end')
    if (lists.length == 0) {
        return ctx.err('利润表未初始化')
    }
    console.log(me)
    // let cardsql = """SELECT  sum(iif(c.direct=N'借', price1-price2, price2-price1)) amount from card
    // a INNER JOIN card_info b on a.id=b.cardId
    // inner join category c on b.subjectId=c.id and a.tenantId=#{tenantId} and a.billState='accounted' """
    // for (profit in lists) {
    //     profit.ym = ym
    //     if (not_blank(profit.subjectCode) && not_null(profit.direct)) {
    //         let scode = profit.subjectCode
    //         let listM = []
    //         let listY = []
    //         if (scode.equals("6711")) {
    //             listY = db.select(cardsql + " and a.billDate between #{yb} and #{me} and (subjectCode like '${scode}%' or subjectCode like '6710%'  )  ")
    //             listM = db.select(cardsql + " and a.billDate between #{mb} and #{me} and (subjectCode like '${scode}%' or subjectCode like '6710%'  ) ")
    //         } else {
    //             listY = db.select(cardsql + " and a.billDate between #{yb} and #{me} and subjectCode like '${scode}%' ")
    //             listM = db.select(cardsql + " and a.billDate between #{mb} and #{me} and subjectCode like '${scode}%'")
    //         }
    //         profit.amountM = listM.size() > 0 ? listM[0].amount : 0
    //         profit.amountY = listY.size() > 0 ? listY[0].amount : 0
    //     }
    // }
    // let a0m = not_null(lists[0].amountM) ? lists[0].amountM.asDecimal() : '0'.asDecimal()
    // let a1m = not_null(lists[1].amountM) ? lists[1].amountM.asDecimal() : '0'.asDecimal()
    // let a2m = not_null(lists[2].amountM) ? lists[2].amountM.asDecimal() : '0'.asDecimal()
    // let a3m = not_null(lists[3].amountM) ? lists[3].amountM.asDecimal() : '0'.asDecimal()
    // let a4m = not_null(lists[4].amountM) ? lists[4].amountM.asDecimal() : '0'.asDecimal()
    // let a5m = not_null(lists[5].amountM) ? lists[5].amountM.asDecimal() : '0'.asDecimal()
    // let a6m = not_null(lists[6].amountM) ? lists[6].amountM.asDecimal() : '0'.asDecimal()
    // let a7m = not_null(lists[7].amountM) ? lists[7].amountM.asDecimal() : '0'.asDecimal()
    // let a8m = not_null(lists[8].amountM) ? lists[8].amountM.asDecimal() : '0'.asDecimal()
    // let a9m = not_null(lists[9].amountM) ? lists[9].amountM.asDecimal() : '0'.asDecimal()
    // let a10m = not_null(lists[10].amountM) ? lists[10].amountM.asDecimal() : '0'.asDecimal()
    // let a11m = not_null(lists[11].amountM) ? lists[11].amountM.asDecimal() : '0'.asDecimal()
    // let a12m = not_null(lists[12].amountM) ? lists[12].amountM.asDecimal() : '0'.asDecimal()
    // let a13m = not_null(lists[13].amountM) ? lists[13].amountM.asDecimal() : '0'.asDecimal()
    // //
    // let a0y = not_null(lists[0].amountY) ? lists[0].amountY.asDecimal() : '0'.asDecimal()
    // let a1y = not_null(lists[1].amountY) ? lists[1].amountY.asDecimal() : '0'.asDecimal()
    // let a2y = not_null(lists[2].amountY) ? lists[2].amountY.asDecimal() : '0'.asDecimal()
    // let a3y = not_null(lists[3].amountY) ? lists[3].amountY.asDecimal() : '0'.asDecimal()
    // let a4y = not_null(lists[4].amountY) ? lists[4].amountY.asDecimal() : '0'.asDecimal()
    // let a5y = not_null(lists[5].amountY) ? lists[5].amountY.asDecimal() : '0'.asDecimal()
    // let a6y = not_null(lists[6].amountY) ? lists[6].amountY.asDecimal() : '0'.asDecimal()
    // let a7y = not_null(lists[7].amountY) ? lists[7].amountY.asDecimal() : '0'.asDecimal()
    // let a8y = not_null(lists[8].amountY) ? lists[8].amountY.asDecimal() : '0'.asDecimal()
    // let a9y = not_null(lists[9].amountY) ? lists[9].amountY.asDecimal() : '0'.asDecimal()
    // let a10y = not_null(lists[10].amountY) ? lists[10].amountY.asDecimal() : '0'.asDecimal()
    // let a11y = not_null(lists[11].amountY) ? lists[11].amountY.asDecimal() : '0'.asDecimal()
    // let a12y = not_null(lists[12].amountY) ? lists[12].amountY.asDecimal() : '0'.asDecimal()
    // let a13y = not_null(lists[13].amountY) ? lists[13].amountY.asDecimal() : '0'.asDecimal()
    // a0m = a1m.asDecimal().add(a2m)
    // a0y = a1y.asDecimal().add(a2y)
    // lists[0].amountM = a0m
    // lists[0].amountY = a0y
    // // 营业利润
    // a8m = a0m.asDecimal().subtract(a3m).subtract(a4m).subtract(a5m).subtract(a6m).subtract(a7m)
    // a8y = a0y.asDecimal().subtract(a3y).subtract(a4y).subtract(a5y).subtract(a6y).subtract(a7y)
    // lists[8].amountM = a8m
    // lists[8].amountY = a8y
    // // 利润总额
    // a11m = a8m.add(a9m).subtract(a10m)
    // a11y = a8y.add(a9y).subtract(a10y)
    // lists[11].amountM = a11m
    // lists[11].amountY = a11y
    // // 净利润
    // lists[13].amountM = a11m.subtract(a12m)
    // lists[13].amountY = a11y.subtract(a12y)
    // // 写入当前利润表
    // db.update("delete from profit_current where tenantId=#{tenantId}")
    // for (it in lists) {
    //     let save = {
    //         tenantId,
    //         code: it.code,
    //         name: it.name,
    //         op: it.op,
    //         amountM: it.amountM ? it.amountM : 0,
    //         amountY: it.amountY ? it.amountY : 0,
    //         amountM3: 0,
    //         isSum: it.isSum,
    //         disabled: it.disabled,
    //         space: it.space,
    //         click: it.click,
    //         isSubject: it.isSubject,
    //         subjectName: it.subjectName,
    //         subjectCode: it.subjectCode,
    //         direct: it.direct,
    //         hasChild: it.hasChild,
    //         ym: it.ym
    //     }
    //     db.table('profit_current').withBlank().primary('id').save(save)
    // }
    // return suc('', lists)
}

module.exports = router;
